package com.atguigu.yygh.msm.controller;

import com.atguigu.yygh.common.R;
import com.atguigu.yygh.msm.service.MsmService;
import com.atguigu.yygh.msm.utils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@Api(tags = "短信服务接口")
@RestController
@RequestMapping("/api/msm")
public class MsmController {
    @Autowired
    private MsmService msmService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @ApiOperation(value = "发送验证码短信")
    @GetMapping(value = "/send/{phone}")
    public R code(@PathVariable String phone) {
        //根据手机号查询验证码
        String redisCode = redisTemplate.opsForValue().get(phone);
        //如果存在，直接返回成功
        if (!StringUtils.isEmpty(redisCode)) {
            return R.ok();
        }
        //不存在，生成验证码，封装参数
        String code = RandomUtil.getFourBitRandom();
        HashMap<String, Object> params = new HashMap<>();
        params.put("code", code);
        //调用方法，发送短信
        boolean isSend = msmService.send(phone, params);
        if (isSend) {
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
            return R.ok();
        } else {
            return R.error().message("发送验证码失败");
        }
    }
}
